﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PearTunes.Model;
using PearTunes.WEB.Models;
using System.IO;
using TagLib;

namespace PearTunes.WEB.Controllers
{
    /// <summary>
    /// Controller class for actions involving home pages, money accounts and music management.
    /// </summary>
    [HandleError]
    public class HomeController : Controller
    {
        /// <summary>
        /// Shows a basic screen with login and register options, or the
        /// home view for logged in users, depending on their role.
        /// </summary>
        public ActionResult Index()
        {
            ViewData["Message"] = "Üdv a PearTunes web felületén!";
            if (User.Identity.IsAuthenticated)
            {
                if(User.IsInRole("administrator"))
                    return RedirectToAction("AdminHome");
                else
                    return RedirectToAction("UserHome");
            }
            else return View();
        }

        /// <summary>
        /// Shows a simple information page.
        /// </summary>
        public ActionResult About()
        {
            return View();
        }

        /// <summary>
        /// Creates a new track from the uploaded file, forwards it to the MusicModel, and saves the uploaded file.
        /// <para>Returns to the track upload page.</para>
        /// <para>Avaiable only for administrators.</para>
        /// </summary>
        [Authorize(Roles = "administrator")]
        public ActionResult NewTrack()
        {
            if (Request.Files.Count > 0)
            {
                Request.Files[0].SaveAs("C:\\pearmusic\\temp.mp3");
                TagLib.File temp = TagLib.File.Create("C:\\pearmusic\\temp.mp3");
                MusicModel m = new MusicModel();
                Album album = m.SearchForAlbum(temp.Tag.Album);
                if (album == null)
                {
                    album = new Album()
                    {
                        Title = temp.Tag.Album,
                        //AlbumId = m.GenerateAlbumId(), --Entity framework-nél nem kell
                        Year = (int)temp.Tag.Year,
                        Tracks = new List<Track>()
                    };
                }
                List<Album> albumlist = new List<Album>();
                albumlist.Add(album);

                Track newTrack = new Track()
                {
                    Albums = albumlist,
                    Artist = temp.Tag.FirstPerformer,
                    Genre = temp.Tag.FirstGenre, // az összes kéne bele..
                    Title = (temp.Tag.Title == null || temp.Tag.Title == "") ? Request.Files[0].FileName : temp.Tag.Title,
                    TrackNumber = (int)temp.Tag.Track,
                    Price = 1                    
                };
                string path = String.Format(@"Music/{0}.mp3", m.GenerateRandomFileName());
                newTrack.FilePath = @"http://localhost:2913/"+path;
                album.Tracks = new List<Track>();
                album.Tracks.Add(newTrack);
                m.NewTrack(newTrack);
                Request.Files[0].SaveAs(Server.MapPath("../"+path));
            }
            return View();
        }

        /// <summary>
        /// Lists all the tracks.
        /// </summary>
        [Authorize]
        public ActionResult ListTracks()
        {
            return View(new MusicModel().ListTracks());
        }

        /// <summary>
        /// Forwards a trackID for deletion towards the MusicModel, and redirects back to
        /// the ListTracks page, regardless of the success of the operation.
        /// <para>Avaiable only for administrators.</para>
        /// </summary>
        /// <param name="id">The identifier of the track to delete</param>
        /// <returns>Redirects to ListTracks</returns>
        [Authorize(Roles = "administrator")]
        public ActionResult DeleteTrack(string id)
        {
            MusicModel m = new MusicModel();
            IEnumerable<Track> tr = m.ListTracks().Where(t => t.TrackId == int.Parse(id));
            if (tr.Count() > 0)
            {
                string filename = Path.GetFileName(tr.First().FilePath);
                string path = (Directory.GetParent(Server.MapPath(filename))).Parent.Parent.FullName;
                FileInfo fi = new FileInfo(path + "/Music/" + filename);
                if(fi.Exists)
                    fi.Delete();
                m.DeleteTrack(int.Parse(id));
            }
            return RedirectToAction("ListTracks");
        }

        /// <summary>
        /// Lists all the albums.
        /// </summary>
        [Authorize]
        public ActionResult ListAlbums()
        {
            return View(new MusicModel().ListAlbums());
        }

        /// <summary>
        /// Provides the home view for administrators.
        /// <para>Avaiable only for administrators.</para>
        /// </summary>
        [Authorize(Roles = "administrator")]
        public ActionResult AdminHome()
        {
            return View();
        }

        /// <summary>
        /// Provides the home view for regular users.
        /// </summary>
        [Authorize]
        public ActionResult UserHome()
        {
            return View();
        }

        /// <summary>
        /// A page for downloading the client application.
        /// <para>Avaiable for any registered user.</para>
        /// </summary>
        [Authorize]
        public ActionResult ClientDownload()
        {
            return View();
        }

        /// <summary>
        /// Provides information for the logged in user about the status of their money account,
        /// and a way to transfer money to their account.
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult Money()
        {
            return View((new UserModel()).UserInfo(User.Identity.Name));
        }

        
        /// <summary>Adds 1000 to the user's account.</summary>
        [Authorize]
        [HttpPost]
        public ActionResult AddMoney()
        {
            UserModel um = new UserModel();
            um.AddMoney(User.Identity.Name, 1000);
            return RedirectToAction("Money");
        }

        /// <summary>
        /// Provides a list of all the registered users.
        /// <para>Avaiable only for administrators.</para>
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles="administrator")]
        public ActionResult ManageUsers()
        {
            return View((new UserModel()).ListUsers());
        }

        /// <summary>
        /// Forwards a userID for deletion towards the UserModel, and redirects back to
        /// the ManageUsers page, regardless of the success of the operation.
        /// <para>Avaiable only for administrators.</para>
        /// </summary>
        /// <param name="id">The identifier of the user to delete</param>
        /// <returns>Redirects to ManageUsers</returns>
        [Authorize(Roles = "administrator")]
        public ActionResult DeleteUser(string id)
        {
            (new UserModel()).DeleteUser(int.Parse(id));
            return RedirectToAction("ManageUsers");
        }
    }
}
